/**
 * 
 */
package ar.com.greensoft.neosystem.model.constraint;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import ar.com.greensoft.neosystem.model.PersonaFisica;
import ar.com.greensoft.neosystem.model.references.Sexo;

/**
 * 
 * @author Jorge E. Villaverde
 * @since 23/01/2012
 * @version 1.0.0
 */
public class PersonaFisicaContraintsValidator implements ConstraintValidator<PersonaFisicaContraints, PersonaFisica> {
	private static final String PERSONA_FISICA_INVALID_CUIT_MESSAGE = "{ar.com.greensoft.neosystem.crm.model.PersonaFisica.cuit.message}";
	private static final String PERSONA_FISICA_INVALID_CUIT_SEXO_MESSAGE = "{ar.com.greensoft.neosystem.crm.model.PersonaFisica.cuit_sexo.message}";

	@Override
	public void initialize(PersonaFisicaContraints constraintAnnotation) {
	}

	@Override
	public boolean isValid(PersonaFisica value, ConstraintValidatorContext context) {
		boolean isValid = false;
		boolean cuitPersonaFisica = false;
		boolean cuitSexo = false;
		
		String type = value.getCuit().substring(0, 2);
		Integer nType = 0;
		try{
			nType = Integer.parseInt(type);
			if((nType == 20 || nType == 23 || nType == 27)){
				cuitPersonaFisica = true;
				if(nType == 23){
					cuitSexo = true;
				}else{
					if(Sexo.HOMBRE.equals(value.getSexo()) && (nType == 20) ||
					   Sexo.MUJER.equals(value.getSexo())  && (nType == 27)){
						cuitSexo = true;						
					}
				}
			}
		}catch (NumberFormatException ne){
		}		
				
		isValid = cuitPersonaFisica && cuitSexo;
		
        if(!isValid) {
        	context.disableDefaultConstraintViolation();
        	
        	if(cuitPersonaFisica == false){
	        	context.buildConstraintViolationWithTemplate(
	        			PERSONA_FISICA_INVALID_CUIT_MESSAGE)
	        			.addNode("cuit")
	        			.addConstraintViolation();
        	}
        	if(cuitSexo == false){
	        	context.buildConstraintViolationWithTemplate(
	        			PERSONA_FISICA_INVALID_CUIT_SEXO_MESSAGE)
	        			.addNode("cuit")
	        			.addNode("sexo")
	        			.addConstraintViolation();
        	}        	
        }
				
        return isValid;
	}

}
